package com.xr.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.xr.constant.MessageConstant;
import com.xr.constant.RedisMessageConstant;
import com.xr.exception.CustomException;
import com.xr.pojo.Order;
import com.xr.result.Result;
import com.xr.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Map;

@RestController
@RequestMapping("order")
public class OrderMobileController {
    @Autowired
    private JedisPool jedisPool;
    @Reference
    private OrderService orderService;

    //由于页面传递过来的数据是以JSON格式数据传递过来的，并且我们暂无直接的实体可以接收数据，所以使用map
    @RequestMapping("/submit")
    public Result submit(@RequestBody Map<String, String> paraMap) throws CustomException {
        //获取前台提交过来的手机验证码
        String telephone = paraMap.get("telephone");
        //获取从redis缓存中存储的验证码
        String codeInRedis = jedisPool.getResource().get(telephone+"_"+RedisMessageConstant.SENDTYPE_ORDER);
        System.out.println("left --- joins"+codeInRedis);
        //获取页面上的验证码
        String validateCode = paraMap.get("validateCode");

        System.out.println("left --- join "+validateCode);
        //校验页面输入的验证码是否输入正确
        if(codeInRedis==null||!codeInRedis.equals(validateCode)){
            //验证码输入错误
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
        //如果验证码输入成功，则调用体检预约服务、
        Result result = null;
        try {
            result = orderService.addOrder(paraMap);
            return new Result(true,MessageConstant.ORDER_SUCCESS,result);
        }catch (Exception e){
            e.printStackTrace();
        }
        return new Result(true, MessageConstant.ORDER_SUCCESS);
    }


    @RequestMapping("/findById")
    public Result findById(Integer id) {
        try {
            Order byId = orderService.findById(id);
            return new Result(true, MessageConstant.QUERY_ORDER_SUCCESS, byId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(false, MessageConstant.QUERY_ORDER_FAIL);
    }

}
